package com.mail.anteater.util;

import java.text.SimpleDateFormat;
import java.util.Date;

public class StringDate {

	public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	public static final String SHORT_DATE_FORMAT = "yyyy-MM-dd";

	public static final String BEGIN_TIME = "00:00:00";
	public static final String END_TIME = "23:59:59";
	
	private String date;
	private String dateFormat;

	public StringDate(DATE_TYPE dateType, String date, String oriDateFormat) {
		dateFormat = dateType.equals(DATE_TYPE.SHORT_DATE) ? SHORT_DATE_FORMAT : DATE_FORMAT;
		this.date = parseDate(date, oriDateFormat);
	}

	public StringDate(DATE_TYPE dateType, Date date) {
		dateFormat = dateType.equals(DATE_TYPE.SHORT_DATE) ? SHORT_DATE_FORMAT : DATE_FORMAT;
		this.date = parseDate(date);
	}

	public Date toDate() {
		SimpleDateFormat format = new SimpleDateFormat(dateFormat);
		Date date;
		try {
			date = format.parse(this.date);
		} catch (Exception e) {
			date = null;
		}
		return date;
	}

	@Override
	public String toString() {
		return this.date;
	}

	public enum DATE_TYPE {
		SHORT_DATE, LONG_DATE
	}

	public void setTime(String time){
		if(date != null && !"".equals(date)){
			if(this.dateFormat.equals(SHORT_DATE_FORMAT)){
				dateFormat = DATE_FORMAT;
				date = date + " " + time;
			}else if(this.dateFormat.equals(DATE_FORMAT)){
				date = date.substring(0, 10) + " " + time;
			}	
		}
	}
	
	private String parseDate(String date, String dateFormat) {
		SimpleDateFormat oriFormat = new SimpleDateFormat(dateFormat);
		SimpleDateFormat desireFormat = new SimpleDateFormat(this.dateFormat);
		Date myDate;
		String desireDate;
		try {
			myDate = oriFormat.parse(date);
			desireDate = desireFormat.format(myDate);
		} catch (Exception e) {
			desireDate = null;
		}

		return desireDate;
	}

	private String parseDate(Date date) {
		SimpleDateFormat desireFormat = new SimpleDateFormat(this.dateFormat);
		String desireDate;
		try {
			desireDate = desireFormat.format(date);
		} catch (Exception e) {
			desireDate = null;
		}
		return desireDate;
	}
}
